﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SES.CMS.BL;
using SES.CMS.DO;
using System.Drawing;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace SES.CMS.AdminCP
{
    public partial class Image : System.Web.UI.Page
    {
        MediaDO objMedia = new MediaDO();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Functions.ddlDatabinder(ddlProduct, cmsProductDO.PRODUCTID_FIELD, cmsProductDO.PRODUCTTITLE_FIELD, new cmsProductBL().SelectAll());
                Functions.ddlDatabinder(ddlAlbum, cmsAlbumDO.ALBUMID_FIELD, cmsAlbumDO.TITLE_FIELD, new cmsAlbumBL().SelectAll());
            }
            if (Request.QueryString["ImageID"] != null)
            {
                objMedia.MediaID = int.Parse(Request.QueryString["ImageID"].ToString());
                initForm();
            }
        }

        private void initForm()
        {
            objMedia = new MediaBL().Select(objMedia);

            txtTitle.Text = objMedia.Title;
            txtDetail.Text = objMedia.Description;
            try
            {
                ddlAlbum.SelectedValue = objMedia.AlbumID.ToString();
                ddlProduct.SelectedValue = objMedia.ProductID.ToString();
                txtOrder.Text = objMedia.OrderID.ToString();
            }
            catch
            {

                throw;
            }
            if (objMedia.MediaType == true) // Image - dung MediaFile
            {
                rdImage.Checked = true;
                if (!string.IsNullOrEmpty(objMedia.MediaFile))
                {
                    hplImage.Visible = true;
                    hplImage.NavigateUrl = "/Media/" + objMedia.MediaFile;
                }
            }
            else // Video - Dung MediaUrl
            {
                rdVideo.Checked = true;
                txtVideo.Text = "http://youtu.be/" + objMedia.MediaUrl;
            }
            cbIsHomePage.Checked = objMedia.IsHomePage;

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            MediaBL mediaBL = new MediaBL();
            initObject();

            if (objMedia.MediaID <= 0)
            {
                int mediaID = mediaBL.Insert(objMedia);
                if (cbIsHomePage.Checked)
                    mediaBL.UpdateHomePageVideo(mediaID);
            }
            else
            {
                mediaBL.Update(objMedia);
                if (cbIsHomePage.Checked)
                    mediaBL.UpdateHomePageVideo(objMedia.MediaID);
            }
            Functions.Alert("Cập nhật thành công!", "/Admincp/ListImages.aspx");
        }
        private void initObject()
        {
            objMedia = new MediaBL().Select(objMedia);
            if (txtTitle.Text.Equals(""))
            {
                objMedia.MediaFile = "Không có tiêu đề - ";
            }
            else
            {
                objMedia.MediaFile = txtTitle.Text;
            }
            objMedia.Title = txtTitle.Text;
            objMedia.Description = txtDetail.Text;
            objMedia.AlbumID = int.Parse(ddlAlbum.SelectedValue);
            objMedia.ProductID = int.Parse(ddlProduct.SelectedValue);
            try
            {
                objMedia.OrderID = int.Parse(txtOrder.Text.Trim());

                if (fuImage.HasFile && txtVideo.Text == "")
                {
                    objMedia.MediaFile = UploadFile(fuImage,objMedia.MediaFile);
                }
                else if (!fuImage.HasFile && txtVideo.Text != "")
                {
                    string s = txtVideo.Text;
                    objMedia.MediaUrl = s.Substring(s.LastIndexOf("/") + 1);
                }
            }
            catch
            {
                throw;
            }
            if (rdVideo.Checked)
                objMedia.MediaType = false;
            if (rdImage.Checked)
                objMedia.MediaType = true;
            objMedia.IsHomePage = cbIsHomePage.Checked;
            objMedia.DateUpload = DateTime.Now;
        }
        private string UploadFile(FileUpload fulImages, string title)
        {
            if (!string.IsNullOrEmpty(fulImages.FileName))
            {
                string FileName = string.Format("{0}{1}", Functions.Change_AV(title) + "-" + DateTime.Now.ToString("ddMMyyyyhhmmss"), fulImages.FileName.Substring(fulImages.FileName.LastIndexOf(".")));

                string preName = Functions.Change_AV(title) + "-" + DateTime.Now.ToString("ddMMyyyyhhmmss");
                string typeName = fulImages.FileName.Substring(fulImages.FileName.LastIndexOf("."));

                string SaveLocation = string.Format("{0}\\{1}", Server.MapPath("~/Media/"), FileName);
                fulImages.SaveAs(SaveLocation);

                objMedia.Thumbnail = preName + "_thumbnail" + typeName;

                string pathAvatars = Server.MapPath("~/Media/thumbnail/");
                try
                {
                    int thumbWidth = 400;
                    int thumbHeight = 300;
                    System.Drawing.Image oImg = System.Drawing.Image.FromStream(fulImages.PostedFile.InputStream);
                    System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);
                    Graphics oGraphic = Graphics.FromImage(oThumbNail);
                    oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                    oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                    oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                    oGraphic.DrawImage(oImg, oRectangle);
                    oThumbNail.Save(pathAvatars + objMedia.Thumbnail, ImageFormat.Jpeg);
                    oImg.Dispose();
                }
                catch (Exception ex)
                {
                    Response.Write("Error: " + ex.Message);
                }

                string FilePreWatermark = Server.MapPath(@"~/Media/") + FileName;
                ///Key of Open file
                FileStream fs = new FileStream(FilePreWatermark, FileMode.Open);
                Bitmap bmp = new Bitmap(fs);
                fs.Close();
                ///ohshit
                Graphics canvas = Graphics.FromImage(bmp);
                Bitmap bmpNew = new Bitmap(bmp.Width, bmp.Height);
                canvas = Graphics.FromImage(bmpNew);
                canvas.DrawImage(bmp, new Rectangle(0, 0, bmpNew.Width, bmpNew.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel);
                bmp = bmpNew;

                canvas.DrawString("www.topbike.vn", new Font("Arial", 14, FontStyle.Italic), new SolidBrush(Color.Red), (bmp.Width - 190), (bmp.Height - 25));
                string NewFileName = Server.MapPath(@"~/Media/") + FileName;

                bmp.Save(NewFileName, System.Drawing.Imaging.ImageFormat.Jpeg);

                bmp.Dispose();
                bmpNew.Dispose();

                return FileName;
            }
            return string.Empty;
        }
    }
}